using Domain;
using ErrorCode;
using MediatR;
using Microsoft.Extensions.Logging;
using SqlSugar;
using WriteAPI.Command.Material;

namespace WriteAPI.CommandHandle.Material
{
    /// <summary>
    /// 删除物料补货单及其明细的命令处理器
    /// </summary>
    public class DelMaterialReplenishmentWithDetailsCommandHandler : IRequestHandler<DelMaterialReplenishmentWithDetailsCommand, APIResult<object>>
    {
        private readonly ISqlSugarClient db;
        private readonly ILogger<DelMaterialReplenishmentWithDetailsCommandHandler> logger;

        /// <summary>
        /// 构造函数
        /// </summary>
        public DelMaterialReplenishmentWithDetailsCommandHandler(
            ISqlSugarClient db,
            ILogger<DelMaterialReplenishmentWithDetailsCommandHandler> logger)
        {
            this.db = db ?? throw new ArgumentNullException(nameof(db));
            this.logger = logger ?? throw new ArgumentNullException(nameof(logger));
        }

        /// <summary>
        /// 处理删除请求
        /// </summary>
        public async Task<APIResult<object>> Handle(
            DelMaterialReplenishmentWithDetailsCommand request,
            CancellationToken cancellationToken)
        {
            var result = new APIResult<object>();

            try
            {
                // 使用事务确保数据一致性
                await Task.Run(() =>
                {
                    db.Ado.UseTran(() =>
                    {
                        // 删除关联明细记录
                        int detailCount = db.Deleteable<MaterialDetail>()
                            .Where(p => p.UpId == request.Id)
                            .ExecuteCommand();

                        logger.LogInformation($"已删除 {detailCount} 条物料明细记录");

                        // 删除主表记录
                        int masterCount = db.Deleteable<MaterialReplenishment>()
                            .Where(x => x.DocCode == request.Id)
                            .ExecuteCommand();

                        if (masterCount == 0)
                        {
                            throw new Exception($"未找到要删除的补货单记录: {request.Id}");
                        }

                        logger.LogInformation($"已删除补货单记录: {request.Id}");
                    });
                });

                result.Code = 200;
                result.Message = "删除成功";
            }
            catch (Exception ex)
            {
                logger.LogError(ex, $"删除补货单 {request.Id} 失败");
                result.Code = 500;
                result.Message = ex.Message;
            }

            return result;
        }
    }
}
